package com.yizisu.playerlibrary.service.download

import android.app.Notification
import android.content.Context
import com.google.android.exoplayer2.offline.Download
import com.google.android.exoplayer2.offline.DownloadManager
import com.google.android.exoplayer2.ui.DownloadNotificationHelper
import com.google.android.exoplayer2.util.NotificationUtil
import com.google.android.exoplayer2.util.Util
import java.lang.Exception

class TerminalStateNotificationHelper(
    private val context: Context,
    private val notificationHelper: DownloadNotificationHelper,
    private var nextNotificationId: Int,
) : DownloadManager.Listener {

    override fun onDownloadChanged(
        downloadManager: DownloadManager,
        download: Download,
        finalException: Exception?
    ) {
        val notification: Notification?
        when (download.state) {
            Download.STATE_COMPLETED -> {
                notification =
                    notificationHelper.buildDownloadCompletedNotification(
                        context,
                        android.R.drawable.stat_sys_download_done,
                        /* contentIntent= */ null,
                        Util.fromUtf8Bytes(download.request.data)
                    )
            }
            Download.STATE_FAILED -> {
                notification =
                    notificationHelper.buildDownloadFailedNotification(
                        context,
                        android.R.drawable.stat_sys_download,
                        /* contentIntent= */ null,
                        Util.fromUtf8Bytes(download.request.data)
                    )
            }
            else -> {
                return
            }
        }
        nextNotificationId++
        NotificationUtil.setNotification(context, nextNotificationId, notification)
    }
}